package cz.data.domain.masterdata.controller;

import cz.data.common.base.SimpleDataResponse;
import cz.data.common.core.DataSelectOption;
import cz.data.common.support.metadata.EsDataTypeEnum;
import cz.data.common.support.metadata.PostgresqlDataTypeEnum;
import cz.data.common.support.metadata.SqlserverDataTypeEnum;
import cz.data.common.support.DataTypeEnum;
import cz.data.common.support.metadata.JavaTypeEnum;
import cz.data.common.support.db.DbType;
import cz.data.common.support.metadata.MysqlDataTypeEnum;
import cz.data.common.support.metadata.OracleDataTypeEnum;
import cz.data.common.support.metadata.VerticaDataTypeEnum;
import cz.data.domain.metadata.model.entity.MetadataSourceEntity;
import cz.data.domain.metadata.rpc.MetadataSourceFeign;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
public class ModelTypeController {

    @Resource
    MetadataSourceFeign metadataSourceFeign;

    @GetMapping("/model/type/selectOptions")
    public SimpleDataResponse<List<DataSelectOption>> getModelTypeSelectOption(
            @RequestParam(value = "source", required = false) String sourceId,
            @RequestParam(value = "type", required = false) String dbType) {
        DbType type = Optional.ofNullable(sourceId)
                .map(metadataSourceFeign::getMetadataSourceById)
                .map(MetadataSourceEntity::getDbType)
                .map(DbType::getDbType)
                .orElseGet(() -> Optional.ofNullable(DbType.getDbType(dbType)).orElse(DbType.MYSQL));
        DataTypeEnum[] dataTypeEnumArray;
        switch (type) {
            case ORACLE:
                dataTypeEnumArray = OracleDataTypeEnum.values();
                break;
            case POSTGRE_SQL:
                dataTypeEnumArray = PostgresqlDataTypeEnum.values();
                break;
            case SQL_SERVER:
            case SQL_SERVER2008:
                dataTypeEnumArray = SqlserverDataTypeEnum.values();
                break;
            case MYSQL:
            case MARIADB:
                dataTypeEnumArray = MysqlDataTypeEnum.values();
                break;
            case VERTICA:
                dataTypeEnumArray = VerticaDataTypeEnum.values();
                break;
            case ELASTICSEARCH:
                dataTypeEnumArray = EsDataTypeEnum.values();
                break;
            default:
                dataTypeEnumArray = JavaTypeEnum.values();
        }
        List<DataSelectOption> selectOptions = Arrays.stream(dataTypeEnumArray)
                .map(e -> new DataSelectOption(e.getValue(), e.getTitle(), e.getValue()))
                .collect(Collectors.toList());
        return new SimpleDataResponse<>(selectOptions);
    }
}
